package com.spsyry.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.spsyry.common.core.domain.R;
import com.spsyry.common.core.utils.StringUtils;
import com.spsyry.product.domain.Product;
import com.spsyry.product.mapper.ProductMapper;
import com.spsyry.product.service.IProductOptsService;
import com.spsyry.product.service.IProductService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 商品表Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-09-28
 */
@Service
public class ProductOptsServiceImpl implements IProductOptsService
{
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private IProductService iProductService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public R listAll() {
        List<Product> products = productMapper.selectProductList(null);
        for (Product product : products) {
            redisTemplate.opsForValue().set(String.valueOf(product.getId()),String.valueOf(product),1,TimeUnit.HOURS);
        }
        return R.ok();
    }
    @Override
    public R add(Product product) {

        //添加商品到mysql
        this.iProductService.insertProduct(product);

        //添加商品到redis
        this.redisTemplate.opsForValue().set(String.valueOf(product.getId()), JSON.toJSONString(product));

        return R.ok();
    }

    @Override
    public R listById(Long id) {

        //从reids获取数据
        Object value = this.redisTemplate.opsForValue().get(String.valueOf(id));
        if(StringUtils.isNotNull(value)){
            return R.ok(JSON.parseObject((String)value,Product.class));
        }
        //从数据库获取数据
        Product product = this.iProductService.selectProductById(id);

        //放到redis中
        this.redisTemplate.opsForValue().set(String.valueOf(product.getId()),JSON.toJSONString(product));

        return R.ok();
    }
    @Override
    public R removeById(long id) {

        this.iProductService.deleteProductById(id);

        this.redisTemplate.delete(String.valueOf(id));

        return R.ok();
    }

    @Override
    public R updateById(Product product) {

        this.iProductService.updateProduct(product);

        this.redisTemplate.opsForValue().set(String.valueOf(product.getId()),JSON.toJSONString(product));

        return R.ok();
    }



}
